package com.ruikong.dazhi.service.impl.baseinfo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.base.PersonnelMapper;
import com.ruikong.dazhi.dao.basicinfo.ShopMapper;
import com.ruikong.dazhi.dao.basicinfo.ShopTypeMapper;
import com.ruikong.dazhi.entity.base.Personnel;
import com.ruikong.dazhi.entity.basicinfo.Shop;
import com.ruikong.dazhi.entity.basicinfo.ShopType;
import com.ruikong.dazhi.model.input.ShopPageInput;
import com.ruikong.dazhi.model.output.ShopPageOutput;
import com.ruikong.dazhi.model.output.TreeMenuOutput;
import com.ruikong.dazhi.service.basicinfo.IShopService;
import com.ruikong.dazhi.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * (Shop)表服务实现类
 *
 * @author HuaJiaYi
 * @since 2020-12-17 10:39:57
 */
@Service("shopService")
public class ShopServiceImpl implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ShopTypeMapper shopTypeMapper;
    @Autowired
    private PersonnelMapper personnelMapper;

    @Override
    public Shop queryById(Integer id) {
        return this.shopMapper.queryById(id);
    }

    @Override
    public Integer insert(Shop shop) {
        shop.setCreateTime(new Date());
        return this.shopMapper.insert(shop);
    }

    @Override
    public Integer update(Shop shop) {
        return this.shopMapper.update(shop);
    }

    @Override
    public Integer deleteById(Integer id) {
        return this.shopMapper.deleteById(id);
    }

    @Override
    public PageInfo<ShopPageOutput> getShopPageInfo(ShopPageInput input) {
        PageHelper.startPage(input.getPageNumber(), input.getPageSize());
        List<ShopPageOutput> shopPageOutput = this.shopMapper.getShopPage(input);
        PageInfo<ShopPageOutput> shopPageOutputPageInfo = new PageInfo<>(shopPageOutput);
        return shopPageOutputPageInfo;
    }

    //    @Override
//    public Integer isExist(Integer id, String shopSn, String shopName) {
//        return this.shopMapper.isExist(id, shopSn, shopName);
//    }
    @Override
    public Integer isExist(Shop shop) {
        return this.shopMapper.isExist(shop);
    }

    @Override
    public Integer isShopExist(String shopSn) {
        return this.shopMapper.isShopExist(shopSn);
    }

    //树状
    @Override
    public List<TreeMenuOutput> queryAllTree() {
        List<TreeMenuOutput> list = new ArrayList<TreeMenuOutput>();
        List<Shop> list_shop = this.shopMapper.queryAllTree();
        TreeMenuOutput menuOutput = new TreeMenuOutput();
        //赋值头数据
        menuOutput.setId(0);
        menuOutput.setpId(-1);
        menuOutput.setName("车间");
        list.add(menuOutput);
        for (int i = 0; i < list_shop.size(); i++) {
            TreeMenuOutput m = new TreeMenuOutput();
            m.setId(list_shop.get(i).getId());
            m.setpId(0);
            m.setName(list_shop.get(i).getShopName());
            list.add(m);
        }

        return list;
    }

    @Override
    public List<Shop> queryAll() {
        return this.shopMapper.queryAllTree();
    }

    @Override
    public List<Shop> getAllUsedShop() {
        return this.shopMapper.selectAllShop();
    }

    @Override
    public BaseResult shopImport(MultipartFile multipartFile, Integer personnelId) {
        BaseResult baseResult = new BaseResult();
        //车间集合
        List<Shop> shopList = new ArrayList<>();
        try {
            //将multipartFileToFile转化为File
            File file = ExcelUtil.multipartFileToFile(multipartFile);
            InputStream inputStream = new FileInputStream(file);
            String fileName = file.getName();
            String suffix = fileName.split("\\.")[1];
            if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                baseResult.setMsg("错误！提交文件格式不正确，请上传excel文件");
                baseResult.setCode(ResultApi.failCode);
                return baseResult;
            }
            //xlsx文件使用XSSFWorkbook，否则使用HSSFWorkbook
            Workbook workbook = suffix.equals("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
            Row row = null;
            Iterator<Row> iterator = sheet.rowIterator();
            int index = 0;
            while (iterator.hasNext()) {
                row = iterator.next();
                //跳过第一行标题行
                if (0 == index) {
                    index++;
                    continue;
                }
                //车间
                Shop shop = new Shop();
                //初始化车间状态——停用
                shop.setState(0);
                //车间编号
                cell = row.getCell(0);
                String shopSn;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，车间编号不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    shopSn = cell.getStringCellValue().trim();
                    if (shopMapper.isShopExist(shopSn) > 0) {
                        baseResult.setMsg(String.format("错误！表格第%s行，车间编号已存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }else {
                        shop.setShopSn(shopSn);
                    }

                }
                //车间名称
                cell = row.getCell(1);
                String shopName;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，车间名称不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    shopName = cell.getStringCellValue().trim();
                    shop.setShopName(shopName);
                }
                //车间类型
                cell = row.getCell(2);
                String shopTypeName;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，车间类型不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    shopTypeName = cell.getStringCellValue().trim();
                    ShopType shopType = this.shopTypeMapper.queryShopTypeByName(shopTypeName);
                    if (shopType == null) {
                        baseResult.setMsg(String.format("错误！表格第%s行，车间类型不存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    } else {
                        shop.setShopTypeId(shopType.getId());
                    }
                }
                //创建时间
                cell = row.getCell(3);
                Date createTime;
                if (cell != null) {
                    createTime = cell.getDateCellValue();
                    shop.setCreateTime(createTime);
                }else{
                    //创建时间不填
                    //以当前时间为准
                    shop.setCreateTime(new Date());
                }


                //创建人
                cell = row.getCell(4);
                String personByName;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    personByName = cell.getStringCellValue().trim();
                    Personnel personnel = this.personnelMapper.queryPersonByName(personByName);
                    if(personnel == null){
                        baseResult.setMsg(String.format("错误！表格第%s行，创建人不存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }else {
                        shop.setUserId(personnel.getPersonnelId());
                    }
                }else{
                    //如果创建为空，则默认为管理员
                    shop.setUserId(personnelId);
                }

                //备注
                cell = row.getCell(5);
                String remarks;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    remarks = cell.getStringCellValue().trim();
                    shop.setRemarks(remarks);
                }
                //车间状态
                cell = row.getCell(6);
                Integer state;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    shop.setState(0);
                }
                if (cell != null) {
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(cell.getNumericCellValue()));
                    state = bigDecimal.intValue();
                    shop.setState(state);
                }
                shopList.add(shop);
                index++;
            }
            baseResult = this.importSave(shopList);
            file.delete();
        } catch (Exception e) {
            baseResult.setCode(ResultApi.errorCode);
            baseResult.setMsg("车间导入时出错");
            e.printStackTrace();
        }
        return baseResult;
    }

    //导入信息保存
    public BaseResult importSave(List<Shop> shopList) {
        BaseResult baseResult = new BaseResult();
        Shop shop = new Shop();
        try {
            for (int i = 0; i < shopList.size(); i++) {
                Shop shopSave = shopList.get(i);
                this.shopMapper.insert(shopSave);
            }
            baseResult.setMsg("导入成功");
            baseResult.setCode(ResultApi.successCode);
        } catch (Exception e) {
            baseResult.setMsg("导入时出错");
            baseResult.setCode(ResultApi.failCode);
            e.printStackTrace();
        }
        return baseResult;
    }

}